package io.github.weiranyi.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

// 定义全局过滤器,Ordered用于指定过滤器执行顺序
@Component
public class BlackListFilter implements GlobalFilter, Ordered {
    // 模拟黑名单【可以去数据库或者redis中查询】
    private static List<String> blackList = new ArrayList<>();

    // 加载该类的时候初始化数据
    static {
        blackList.add("127.0.0.1");
        blackList.add("0:0:0:0:0:0:0:1"); // 模拟本机地址
    }

    /**
     * 过滤器的核心逻辑
     *
     * @param exchange 封装了request和response对象的上下文
     * @param chain    网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获得请求响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获得访客的ip地址
        String hostString = request.getRemoteAddress().getHostString();
        // 判断是否在黑名单中
        if (blackList.contains(hostString)) {
            // 拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //没有授权
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    /**
     * 指定过滤器的执行顺序：返回值表示优先级，数值越小优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
